<template>
  <div>
    为{{ role.roleName }}分配权限<br />

    <ul id="basicTree" class="ztree"></ul>

    <el-button size="small" @click="doDistributePermission">确认分配</el-button>
  </div>
</template>

<script>
import axios from "@/util/request.js";
export default {
  mounted() {
    this.getTree();
  },
  data() {
    return {
      role: {},
    };
  },
  methods: {
    doDistributePermission() {
      // 收集数据
      let roleId = this.role.roleId;


      // 获取树中的所有节点
      var treeObj = $.fn.zTree.getZTreeObj("basicTree");
      var nodes = treeObj.getNodes();
      var flatNodes = treeObj.transformToArray(nodes);
      // 遍历所有节点，把那些被选中的节点找出来
      // 传统写法：
      // let checkedNodes = [];
      // for(let node of flatNodes) {
      //     // 判断当前node是否被选中
      //     if(node.checked && !node.isParent) {
      //         checkedNodes.push(node);
      //     }
      // }

      // 新姿势: es5语法 语法糖
      let checkedNodes = flatNodes.filter((node) => {
        return node.checked;
      });

      let permissionIds = checkedNodes.map((node) => {
        return node.permissionId;
      });


      // 给后端发送请求: roleId  permissionIds
      axios.post("role/distributePermission", {
        "roleId": roleId,
        "permissionIds": permissionIds,
      }).then(r => {
        if(r.code == 200) {
          this.$message.success("分配权限成功")
        } else {
          this.$message.warning("无效分配")
        }
      });
    },
    getTree() {
      axios.post("permission/findAll").then((r) => {
        if (r.code == 200) {
          // 设置参数
          let settings = {
            data: {
              key: {
                name: "permissionName",
              },
              simpleData: {
                enable: true,
                idKey: "permissionId",
                pIdKey: "parentId",
              },
            },
            check: {
              enable: true,
            },
          };
          // 设置树的数据
          let nodes = r.data;
          // 初始化树UI
          $.fn.zTree.init($("#basicTree"), settings, nodes);
          // 直接展开树
          var treeObj = $.fn.zTree.getZTreeObj("basicTree");
          treeObj.expandAll(true);
          // 初始化树，默认选中当前role的权限
          this.initTree();
        }
      });
    },
    initTree() {
      // 收集数据
      let roleId = this.$route.params.roleId;
      let config = {
        headers: {
          "Content-Type": "text/plain",
        },
      };
      // 根据roleId查询role对象，此时查出的role对象还包含权限信息
      axios.post("role/findOne", roleId, config).then((r) => {
        if (r.code == 200) {
          // 获取后端响应的角色
          this.role = r.data;
          // 从角色对象中获取该角色所拥有的权限（数组）
          var permissions = this.role.permissions;

          // 获取ztree对象
          var treeObj = $.fn.zTree.getZTreeObj("basicTree");

          for (var i = 0; i < permissions.length; i++) {
            var permissionId = permissions[i].permissionId;
            // 根据条件获取树节点，条件：permissionId = 4
            var node = treeObj.getNodesByParam(
              "permissionId",
              permissionId,
              null
            )[0];
            // 让树勾选中指定的节点
            treeObj.checkNode(node, true, false);
          }
        }
      });
    },
  },
};
</script>

<style>
</style>